/**
 * 测试libevent的事件机制，通过管道通信；
 * @author: sundx
 * @date: 2020-06-04 16:15:55
 * @Last Modified by: sundx
 * @Last Modified time: 2020-06-04 16:20:55
 */

#include <event2/event.h>
#include <fcntl.h>
#include <iostream>
#include <stdlib.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
  void writeFunc(int fd, short what, void *argc); //声明写回回调函数
  int writeFd = open("fifotest", O_WRONLY | O_NONBLOCK); //打开管道写
  if (writeFd == -1) {
    perror("write error");
    exit(EXIT_FAILURE);
  }
  event_base *base = event_base_new(); //创建base
  event *wrEvent = //创建持续写事件，并设置回调函数
      event_new(base, writeFd, EV_WRITE | EV_PERSIST, writeFunc, nullptr);
  event_add(wrEvent, nullptr); //挂载写事件
  event_base_dispatch(base);   //持续监听写事件直至满足
  event_free(wrEvent);         //释放资源
  event_base_free(base);
  return 0;
}

void writeFunc(int fd, short what, void *argc) {
  static int num = 0;
  dup2(fd, STDOUT_FILENO);
  std::cout << num << std::endl;
  ++num;
  sleep(1);
  return;
}